package com.itheima.demo7;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReceiveMessageDemo {
    public static void main(String[] args) throws IOException {
        //接收数据

        //1.创建DatagramSocket对象（快递公司）
        //细节：
        //接收的时候一定要绑定端口
        //绑定的端口号必须与发送的端口保持一致

        DatagramSocket ds = new DatagramSocket(10086);

        //2.接收数据包
        //创建数组
        byte[] bytes = new byte[1024];
        //将数组打包用于接收数据
        DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
        //接收数据
        //receive该方法是堵塞的，程序会在此死等，直到收到发送端发送的消息
        ds.receive(dp);

        //3.解析数据包
        byte[] data = dp.getData();
        int len = dp.getLength();
        InetAddress address = dp.getAddress();
        int port = dp.getPort();

        System.out.println("接收到数据"+new String(data,0,len));
        System.out.println("该数据是从"+address+"电脑的"+port+"端口发出的");

        //4.释放资源
        ds.close();

    }
}
